use crate::components::{AuthContext, EditorApi, EditorContainer, Entry};
use crate::errors::{log_error, MyResult};
use crate::models::{Note, NoteProfile};
use crate::services::{delete_note, get_note_content, get_note_profiles};
use gloo::console::error;
use stylist::yew::styled_component;
use yew::{platform::spawn_local, prelude::*};
//use crate::config;
//use lazy_static::lazy_static;

#[derive(Properties, PartialEq, Default)]
pub struct AppProps {}

async fn reload_note_profiles(profile_list: UseStateHandle<Vec<NoteProfile>>) -> MyResult<()> {
    let result = get_note_profiles().await?;
    profile_list.set(result.data.clone());
    Ok(())
}
async fn load_note(note_id: u64) -> MyResult<Note> {
    let data = get_note_content(note_id).await?;
    Ok(data.data)
}
#[styled_component]
pub fn App(_props: &AppProps) -> Html {
    let profile_list = use_state(Vec::<NoteProfile>::new);

    {
        let profile_list = profile_list.clone();
        use_effect_with((), move |_| {
            spawn_local(async move {
                log_error(reload_note_profiles(profile_list).await, None);
            });
        });
    }

    let notes_changed = {
        let profile_list = profile_list.clone();
        Callback::from(move |_| {
            let profile_list = profile_list.clone();

            spawn_local(async move {
                log_error(reload_note_profiles(profile_list).await, None);
            });
        })
    };
    let handle_profile_click = {
        Callback::from(move |profile_id: u64| {
            spawn_local(async move {
                let result = load_note(profile_id).await;
                match result {
                    Ok(data) => {
                        EditorApi::set_note_content(&data.content);
                        EditorApi::set_note_id(profile_id);
                        EditorApi::set_note_version(data.version);
                        EditorApi::show_editor_container();
                        EditorApi::set_editor_title(
                            EditorApi::editor_title().as_ref().map(|x| x.as_str()),
                        );
                    }
                    Err(error) => {
                        error!("handle_profile_click error:{:?}", error.to_string());
                    }
                }
            });
        })
    };
    let handle_delete_note = {
        let profile_list = profile_list.clone();
        Callback::from(move |profile_id: u64| {
            let profile_list = profile_list.clone();
            spawn_local(async move {
                log_error(delete_note(profile_id).await, None);
                log_error(reload_note_profiles(profile_list).await, None);
            });
        })
    };

    html! {
        <div class={classes!("pos-relative", "column", "w-100")}>
            <AuthContext>
                <Entry
                    profile_list={(*profile_list).clone()}
                    handle_profile_click={handle_profile_click}
                    handle_delete_note={handle_delete_note}
                    />
                <EditorContainer
                    on_close_click={notes_changed}
                />
            </AuthContext>
        </div>
    }
}
